package entity

import (
	"gitee.com/linxing_3/sr-core/domain/model"
	"gitee.com/linxing_3/sr-core/domain/model/vo"
	"gitee.com/linxing_3/sr-core/utils/id"
	"gitee.com/mkwchecking/sr-admin/apps/admin/do"
	"gitee.com/mkwchecking/sr-admin/pkg/utils/crypto"

	"gorm.io/gorm"
)

func NewSysUser() *SysUser { return &SysUser{} }

type SysUser struct {
	UserId   string        `json:"userId" form:"userId" gorm:"size:64;primaryKey;comment:用户id" search:"type:exact"`          // 用户id
	Username string        `json:"username" form:"username" gorm:"uniqueIndex;size:128;comment:用户账号" search:"type:contains"` // 用户账号
	NickName string        `json:"nickName" form:"nickName" gorm:"size:128;comment:用户昵称" search:"type:contains"`             // 用户昵称
	Status   do.UserStatus `json:"status" form:"status" gorm:"size:4;comment:用户状态"`                                          // 用户状态

	Email  string `json:"email" form:"email" gorm:"size:128;comment:用户邮箱" search:"type:contains"` // 用户邮箱
	Avatar string `json:"avatar" form:"avatar" gorm:"size:128;comment:用户头像"`                      // 用户头像
	Phone  string `json:"phone" form:"phone" gorm:"size:11;comment:用户手机" search:"type:contains"`  // 用户手机

	RoleId string `json:"roleId" form:"roleId" gorm:"size:64;index;comment:角色id" search:"type:exact"` // 角色id
	DeptId string `json:"deptId" form:"deptId" gorm:"size:64;index;comment:部门id" search:"type:exact"` // 部门id
	PostId string `json:"postId" form:"postId" gorm:"size:64;index;comment:岗位id" search:"type:exact"` // 岗位id

	Role *SysRole `json:"role,omitempty" gorm:"->;constraint:OnUpdate:CASCADE,OnDelete:SET NULL"` // 角色
	Dept *SysDept `json:"dept,omitempty" gorm:"->;constraint:OnUpdate:CASCADE,OnDelete:SET NULL"` // 部门
	Post *SysPost `json:"post,omitempty" gorm:"->;constraint:OnUpdate:CASCADE,OnDelete:SET NULL"` // 岗位

	ThridBinds *[]SysUserThirdBind          `json:"-" gorm:"foreignKey:UserId;references:UserId"` // 第三方绑定
	Thirds     map[string]*SysUserThirdBind `json:"thirds,omitempty" gorm:"-"`                    // 第三方绑定

	model.PasswdModel
	model.GAllInject
}

func (SysUser) TableName() string {
	return "sys_user"
}

func (s *SysUser) AfterFind(tx *gorm.DB) (err error) {
	if s.ThridBinds == nil || len(*s.ThridBinds) == 0 {
		return
	}
	s.Password = ""
	s.Thirds = make(map[string]*SysUserThirdBind)
	for _, v := range *s.ThridBinds {
		s.Thirds[v.Platform] = &v
	}
	return
}

func (s *SysUser) BeforeCreate(tx *gorm.DB) error {
	if s.UserId == "" || s.UserId == "0" {
		s.UserId = id.GenIDString()
	}
	var err error
	// if s.Password != "" {
	// s.Password, err = pkg.SetPassword(s.Password, s.Solt)
	// if hash, err := bcrypt.GenerateFromPassword([]byte(s.Password), bcrypt.DefaultCost); err != nil {
	if hash, err := crypto.PasswordHash(s.Password); err != nil {
		return err
	} else {
		s.Password = hash
		s.PassUpdateAt = vo.NewTimeNow().Ptr()
	}
	return err
}
